#include "HandleMgr.h"
#include "ThreadPoolMgr.h"
#include "GlobalDataQueue.h"
#include "LoadConfig.h"
#include <boost/bind.hpp>

IMPL_LOGGER(HandleMgr,logger);

HandleMgr::HandleMgr()
{
    m_recv_client_thread = NULL;
    m_client_cmd_thread  = NULL;
    m_client_cmd_recive.clear();
    m_recive_client_connect.clear();
}

HandleMgr::~HandleMgr()
{
    m_client_cmd_recive.clear();
    m_recive_client_connect.clear();
}

bool HandleMgr::init()
{
    LOG4CPLUS_DEBUG(logger,"start init");

    if(!init_conf())
    {
        LOG4CPLUS_ERROR(logger,"init conf fail");
        return false;
    }

    if(!init_queue())
    {
        LOG4CPLUS_ERROR(logger,"init queue fail");
        return false;
    }
    
    if(!init_thread())
    {
        LOG4CPLUS_ERROR(logger,"init thread fail");
        return false;
    }
    
    LOG4CPLUS_DEBUG(logger,"end init");
    return true;
}

bool HandleMgr::init_thread()
{

    LOG4CPLUS_DEBUG(logger,"start init thread");
    
    RECIVECLIENTCONNECT recv_client(new ReciveClientConnect());
    if(!recv_client)
    {
        LOG4CPLUS_DEBUG(logger,"when create ReciveClientConnect failed");
        return false;
    }
    m_recive_client_connect.push_back(recv_client);
    
    m_recv_client_thread = 
    g_ThreadPool_Mgr::instance().get_thread_pool().create_thread(boost::bind(ReciveClientConnect::start_thread,ref(*recv_client)));

    if(m_recv_client_thread==NULL)
    {
        LOG4CPLUS_ERROR(logger,"create recv client connect fail");
        return false;
    }

    LOG4CPLUS_DEBUG(logger,"create recv client connect succ");


    for( uint32_t i=0;i<g_LoadConfig_Mgr::instance().m_client_cmd_recv_thread_num;++i)
    {
        CLIENTCMDRECIVE recv_cmd(new ClientCmdRecive());
        if(!recv_cmd)
        {
            LOG4CPLUS_DEBUG(logger,"when create ClientCmdRecive failed");
            return false;
        }
        m_client_cmd_recive.push_back(recv_cmd);
        
        m_client_cmd_thread = 
        g_ThreadPool_Mgr::instance().get_thread_pool().create_thread(boost::bind(ClientCmdRecive::start_thread,ref(*recv_cmd)));

        if(m_recv_client_thread==NULL)
        {
            LOG4CPLUS_ERROR(logger,"create client cmd recv thread fail now i: "<<i);
            return false;
        }
    }


    LOG4CPLUS_DEBUG(logger,"end init thread");
    
    return true;
}

bool HandleMgr::init_conf()
{
    LOG4CPLUS_DEBUG(logger,"start init conf");
    

    LOG4CPLUS_DEBUG(logger,"init recv client succ");

    return true;
}

bool HandleMgr::start()
{
    LOG4CPLUS_DEBUG(logger,"start");

    return true;
}

bool HandleMgr::wait_end()
{
    LOG4CPLUS_DEBUG(logger,"start wait end");

    g_ThreadPool_Mgr::instance().join_all();

    return true;
}

bool HandleMgr::init_queue()
{
   return g_GlobalDataQueue_Mgr::instance().init_queue();
}

